package com.nari.ncps.screen.service.impl.electric;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.electric.ElectricOverviewItem;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperFuelMapper;
import com.nari.ncps.screen.service.electric.ElectricOverviewItemService;
import com.nari.ncps.screen.service.electric.ElectricProdoperFuelService;
import com.nari.ncps.screen.vo.electric.CoalStorageAndAvailableDays;
import com.nari.ncps.screen.vo.electric.InventorySituation;
import com.nari.ncps.screen.vo.electric.ProductionStatusVO;
import com.nari.ncps.screen.vo.wholeproduct.AnnualPowerGenerationVO;
import com.nari.ncps.screen.vo.wholeproduct.FuelConsumptionVO;
import com.nari.ncps.screen.entity.electric.ElectricProdoperFuel;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 燃料情况详情表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperFuelServiceImpl extends ServiceImpl<ElectricProdoperFuelMapper, ElectricProdoperFuel> implements ElectricProdoperFuelService {

    @Resource
    private ElectricOverviewItemService electricOverviewItemService;

    /**
     * 燃料进耗存情况
     * @param year 年份（选填，默认当前年）
     * @return 燃料进耗存情况
     */
    @Override
    public InventorySituation inventorySituation(Integer year) {
        // 创建返回对象 qt_dp_electric_prodoper_fuel
        InventorySituation inventorySituation = new InventorySituation();
        inventorySituation.setYear(year);
        
        // 构建查询条件：查询年数据（date_type=0）
        LambdaQueryWrapper<ElectricProdoperFuel> yearQuery = new LambdaQueryWrapper<>();
        yearQuery.eq(ElectricProdoperFuel::getYear, year)
                .eq(ElectricProdoperFuel::getOrgCode,"100360")
                .eq(ElectricProdoperFuel::getDateType, 0);
        List<ElectricProdoperFuel> yearList = this.list(yearQuery);
        
        // 构建查询条件：查询月数据（date_type=1）
        LambdaQueryWrapper<ElectricProdoperFuel> monthQuery = new LambdaQueryWrapper<>();
        monthQuery.eq(ElectricProdoperFuel::getYear, year)
                .eq(ElectricProdoperFuel::getOrgCode,"100360")
                .eq(ElectricProdoperFuel::getDateType, 1);
        List<ElectricProdoperFuel> monthList = this.list(monthQuery);
        
        // 处理年数据，如果查询结果为空，设置默认值为0
        if (yearList != null && !yearList.isEmpty()) {
            // 年数据求和
            inventorySituation.setAnnualPlanCoalIn(
                yearList.stream()
                    .filter(item -> item.getAnnualPlanCoalIn() != null)
                    .map(ElectricProdoperFuel::getAnnualPlanCoalIn)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualActualCoalIn(
                yearList.stream()
                    .filter(item -> item.getAnnualActualCoalIn() != null)
                    .map(ElectricProdoperFuel::getAnnualActualCoalIn)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualCoalInOverShortage(
                yearList.stream()
                    .filter(item -> item.getAnnualCoalInOverShortage() != null)
                    .map(ElectricProdoperFuel::getAnnualCoalInOverShortage)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualCoalInCompletionRate(
                yearList.stream()
                    .filter(item -> item.getAnnualCoalInCompletionRate() != null)
                    .map(ElectricProdoperFuel::getAnnualCoalInCompletionRate)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualPlanCoalConsumption(
                yearList.stream()
                    .filter(item -> item.getAnnualPlanCoalConsumption() != null)
                    .map(ElectricProdoperFuel::getAnnualPlanCoalConsumption)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualActualCoalConsumption(
                yearList.stream()
                    .filter(item -> item.getAnnualActualCoalConsumption() != null)
                    .map(ElectricProdoperFuel::getAnnualActualCoalConsumption)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualCoalConsumptionOverShortage(
                yearList.stream()
                    .filter(item -> item.getAnnualCoalConsumptionOverShortage() != null)
                    .map(ElectricProdoperFuel::getAnnualCoalConsumptionOverShortage)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setAnnualCoalConsumptionCompletionRate(
                yearList.stream()
                    .filter(item -> item.getAnnualCoalConsumptionCompletionRate() != null)
                    .map(ElectricProdoperFuel::getAnnualCoalConsumptionCompletionRate)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
        } else {
            // 年数据为空时设置默认值
            inventorySituation.setAnnualPlanCoalIn(BigDecimal.ZERO);
            inventorySituation.setAnnualActualCoalIn(BigDecimal.ZERO);
            inventorySituation.setAnnualCoalInOverShortage(BigDecimal.ZERO);
            inventorySituation.setAnnualCoalInCompletionRate(BigDecimal.ZERO);
            inventorySituation.setAnnualPlanCoalConsumption(BigDecimal.ZERO);
            inventorySituation.setAnnualActualCoalConsumption(BigDecimal.ZERO);
            inventorySituation.setAnnualCoalConsumptionOverShortage(BigDecimal.ZERO);
            inventorySituation.setAnnualCoalConsumptionCompletionRate(BigDecimal.ZERO);
        }
        
        // 处理月数据，如果查询结果为空，设置默认值为0
        if (monthList != null && !monthList.isEmpty()) {
            // 月数据求和
            inventorySituation.setCurrentFuelStock(
                monthList.stream()
                    .filter(item -> item.getCurrentFuelStock() != null)
                    .map(ElectricProdoperFuel::getCurrentFuelStock)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setDailyCoalConsumption(
                monthList.stream()
                    .filter(item -> item.getDailyCoalConsumption() != null)
                    .map(ElectricProdoperFuel::getDailyCoalConsumption)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            
            inventorySituation.setStockAvailableDays(
                monthList.stream()
                    .filter(item -> item.getStockAvailableDays() != null)
                    .mapToInt(ElectricProdoperFuel::getStockAvailableDays)
                    .sum()
            );
        } else {
            // 月数据为空时设置默认值
            inventorySituation.setCurrentFuelStock(BigDecimal.ZERO);
            inventorySituation.setDailyCoalConsumption(BigDecimal.ZERO);
            inventorySituation.setStockAvailableDays(0);
        }
        
        return inventorySituation;
    }

    /**
     * 各电厂存煤以及可用天数
     * @param year 年份（选填，默认当前年）
     * @return 各电厂各月份的存煤及可用天数列表
     */
    @Override
    public List<CoalStorageAndAvailableDays> coalStorageAndAvailableDays(Integer year) {

        LocalDate currentDate = LocalDate.now();
        LocalDate lastMonthDate = currentDate.minusMonths(1);
        int lastMonth =  lastMonthDate.getMonthValue();

        LambdaQueryWrapper<ElectricProdoperFuel> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperFuel::getDateType, 1)
                        .eq(ElectricProdoperFuel::getMonth, lastMonth);
//        lqw.groupBy(ElectricProdoperFuel::getOrgCode);
        List<ElectricProdoperFuel> fuels = this.list(lqw);
//        List<CoalStorageAndAvailableDays> resultlist =  BeanUtil.copyToList(fuels,CoalStorageAndAvailableDays.class);

        List<CoalStorageAndAvailableDays> resultlist = new ArrayList<>();
        for(ElectricProdoperFuel fuel : fuels) {
            CoalStorageAndAvailableDays vo = new CoalStorageAndAvailableDays();
            vo.setPowerPlantCode(fuel.getOrgCode());
            vo.setPowerPlantName(fuel.getOrgName());
            vo.setYear(fuel.getYear());
            vo.setMonth(fuel.getMonth());
            vo.setWarningAvailableDays(fuel.getWarningAvailableDays());
            vo.setCurrentFuelStock(fuel.getCurrentFuelStock());
            vo.setWarningStock(fuel.getWarningStock());
            vo.setDailyCoalConsumption(fuel.getDailyCoalConsumption());
            vo.setStockAvailableDays(fuel.getStockAvailableDays());
            resultlist.add(vo);
        }
        return resultlist;




 /*
        // 构建查询条件：查询月数据（date_type=1）
        LambdaQueryWrapper<ElectricProdoperFuel> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperFuel::getYear, year)
           .eq(ElectricProdoperFuel::getDateType, 0); // 查询年数据
        List<ElectricProdoperFuel> monthList = this.list(lqw);
        
        // 如果查询结果为空，返回空列表
        if (monthList == null || monthList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 按电厂编码和月份分组统计
        List<CoalStorageAndAvailableDays> resultList = monthList.stream()
                .collect(java.util.stream.Collectors.groupingBy(
                        item -> item.getOrgCode() + "_" + item.getMonth() // 按电厂+月份分组
                ))
                .entrySet()
                .stream()
                .map(entry -> {
                    List<ElectricProdoperFuel> groupDataList = entry.getValue();
                    
                    // 获取电厂编码和月份（取第一条记录的值）
                    ElectricProdoperFuel firstItem = groupDataList.get(0);
                    String powerPlantCode = firstItem.getOrgCode();
                    Integer month = firstItem.getMonth();
                    
                    CoalStorageAndAvailableDays result = new CoalStorageAndAvailableDays();
                    result.setYear(year);
                    result.setMonth(month);
                    result.setPowerPlantCode(powerPlantCode);
                    
                    // 获取电厂名称（取第一个非空的名称）
                    String powerPlantName = groupDataList.stream()
                            .map(ElectricProdoperFuel::getOrgName)
                            .filter(name -> name != null && !name.trim().isEmpty())
                            .findFirst()
                            .orElse("");
                    result.setPowerPlantName(powerPlantName);
                    
                    // 相同电厂、相同月份的数据求和
                    // 当前燃料库存：求和
                    BigDecimal currentFuelStock = groupDataList.stream()
                            .filter(item -> item.getCurrentFuelStock() != null)
                            .map(ElectricProdoperFuel::getCurrentFuelStock)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    result.setCurrentFuelStock(currentFuelStock);
                    
                    // 警戒库存：求和
                    BigDecimal warningStock = groupDataList.stream()
                            .filter(item -> item.getWarningStock() != null)
                            .map(ElectricProdoperFuel::getWarningStock)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    result.setWarningStock(warningStock);
                    
                    // 日均耗煤量：求和
                    BigDecimal dailyCoalConsumption = groupDataList.stream()
                            .filter(item -> item.getDailyCoalConsumption() != null)
                            .map(ElectricProdoperFuel::getDailyCoalConsumption)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    result.setDailyCoalConsumption(dailyCoalConsumption);
                    
                    // 库存可用天数：求和
                    Integer stockAvailableDays = groupDataList.stream()
                            .filter(item -> item.getStockAvailableDays() != null)
                            .mapToInt(ElectricProdoperFuel::getStockAvailableDays)
                            .sum();
                    result.setStockAvailableDays(stockAvailableDays);
                    
                    // 警戒可用天数：求和
                    Integer warningAvailableDays = groupDataList.stream()
                            .filter(item -> item.getWarningAvailableDays() != null)
                            .mapToInt(ElectricProdoperFuel::getWarningAvailableDays)
                            .sum();
                    result.setWarningAvailableDays(warningAvailableDays);
                    
                    return result;
                })
                .sorted((a, b) -> {
                    // 按电厂编码、月份排序
                    int plantCompare = a.getPowerPlantCode().compareTo(b.getPowerPlantCode());
                    if (plantCompare != 0) {
                        return plantCompare;
                    }
                    return a.getMonth().compareTo(b.getMonth());
                })
                .collect(java.util.stream.Collectors.toList());
        
        return resultList;
     */

    }

    /**
     * 获取年度燃料耗存情况（最近5年）
     * @return 年度燃料耗存情况列表
     */
    @Override
    public List<FuelConsumptionVO> getAnnualFuelConsumption() {
        // 从数据库查询年度汇总数据
        List<ElectricProdoperFuel> annualStatsList = baseMapper.getAnnualFuelConsumptionStats();
        
        // 转换为VO对象
        List<FuelConsumptionVO> resultList = new ArrayList<>();
        for(ElectricProdoperFuel data:annualStatsList){
            FuelConsumptionVO vo=new FuelConsumptionVO();
            vo.setYear(data.getYear());
            vo.setCoalConsumptionCompletionRate(data.getAnnualCoalConsumptionCompletionRate());
            vo.setCoalConsumption(data.getAnnualActualCoalIn());
            vo.setCoalInCompletion(data.getAnnualActualCoalConsumption());
            resultList.add(vo);
        }
//        for (ElectricProdoperFuel entity : annualStatsList) {
//            FuelConsumptionVO vo = new FuelConsumptionVO();
//            vo.setYear(entity.getYear());
//            vo.setCoalConsumption(entity.getAnnualActualCoalConsumption());
//            vo.setCoalInCompletion(entity.getAnnualActualCoalIn());
//
//            // 计算耗煤完成率：实际耗煤量 / 计划耗煤量 * 100
//            if (entity.getAnnualPlanCoalConsumption() != null && entity.getAnnualPlanCoalConsumption().compareTo(BigDecimal.ZERO) != 0) {
//                BigDecimal completionRate = entity.getAnnualActualCoalConsumption()
//                        .divide(entity.getAnnualPlanCoalConsumption(), 4, RoundingMode.HALF_UP)
//                        .multiply(new BigDecimal("100"))
//                        .setScale(2, RoundingMode.HALF_UP);
//                vo.setCoalConsumptionCompletionRate(completionRate);
//            } else {
//                vo.setCoalConsumptionCompletionRate(BigDecimal.ZERO);
//            }
//
//            resultList.add(vo);
//        }
        resultList.sort(Comparator.comparingInt(FuelConsumptionVO::getYear));
        return resultList;
    }

    /**
     * 查询生产情况信息
     * @param orgCode 单位编码（可选）
     * @return 生产情况信息，包含日发电量、日均煤耗、库存可用天数
     */
    @Override
    public ProductionStatusVO getProductionStatus(String orgCode) {
        // 获取当前日期
        Date now = new Date();
        Integer year = DateUtil.year(now);
        Integer month = DateUtil.month(now) + 1; // hutool月份从0开始，需要+1
        Integer day = DateUtil.dayOfMonth(now);

        ProductionStatusVO result = new ProductionStatusVO();

        // 1. 查询燃料表获取日均煤耗和库存可用天数
        QueryWrapper<ElectricProdoperFuel> fuelWrapper = new QueryWrapper<>();
        fuelWrapper.eq("year", year);
        fuelWrapper.eq("month", month);
        fuelWrapper.eq("date_type", 1); // 月数据
        if (orgCode != null && !orgCode.isEmpty()) {
            fuelWrapper.eq("org_code", orgCode);
        }
        fuelWrapper.orderByDesc("update_time");
        fuelWrapper.last("LIMIT 1");

        ElectricProdoperFuel fuel = getOne(fuelWrapper);

        // 如果当前月没有数据，查询最近的一条数据
        if (fuel == null) {
            QueryWrapper<ElectricProdoperFuel> fallbackWrapper = new QueryWrapper<>();
            if (orgCode != null && !orgCode.isEmpty()) {
                fallbackWrapper.eq("org_code", orgCode);
            }
            fallbackWrapper.eq("date_type", 1); // 月数据
            fallbackWrapper.orderByDesc("year", "month", "update_time");
            fallbackWrapper.last("LIMIT 1");
            fuel = getOne(fallbackWrapper);
        }

        if (fuel != null) {
            result.setPowerPlantCode(fuel.getOrgCode());
            result.setPowerPlantName(fuel.getOrgName());
            result.setDailyCoalConsumption(fuel.getDailyCoalConsumption() != null ? 
                    fuel.getDailyCoalConsumption() : BigDecimal.ZERO);
            result.setStockAvailableDays(fuel.getStockAvailableDays() != null ? 
                    fuel.getStockAvailableDays() : 0);
        }

        // 2. 查询总览表获取日发电量
        QueryWrapper<ElectricOverviewItem> overviewWrapper = new QueryWrapper<>();
        overviewWrapper.eq("year", year);
        overviewWrapper.eq("month", month);
        overviewWrapper.eq("day", day);
        overviewWrapper.eq("date_type", 2); // 日数据
        if (orgCode != null && !orgCode.isEmpty()) {
            overviewWrapper.eq("org_code", orgCode);
        }
        overviewWrapper.orderByDesc("update_time");
        overviewWrapper.last("LIMIT 1");

        ElectricOverviewItem overview = electricOverviewItemService.getOne(overviewWrapper);

        // 如果当天没有数据，查询最近的一条数据
        if (overview == null) {
            QueryWrapper<ElectricOverviewItem> fallbackOverviewWrapper = new QueryWrapper<>();
            if (orgCode != null && !orgCode.isEmpty()) {
                fallbackOverviewWrapper.eq("org_code", orgCode);
            }
            fallbackOverviewWrapper.eq("date_type", 2); // 日数据
            fallbackOverviewWrapper.orderByDesc("year", "month", "day", "update_time");
            fallbackOverviewWrapper.last("LIMIT 1");
            overview = electricOverviewItemService.getOne(fallbackOverviewWrapper);
        }

        if (overview != null) {
            // 如果之前没有设置电厂信息，从总览表获取
            if (result.getPowerPlantCode() == null || result.getPowerPlantCode().isEmpty()) {
                result.setPowerPlantCode(overview.getOrgCode());
                result.setPowerPlantName(overview.getOrgName());
            }
            result.setDailyPowerGeneration(overview.getDailyGeneration() != null ? 
                    overview.getDailyGeneration() : BigDecimal.ZERO);
        } else {
            // 如果没有查询到总览数据，设置默认值
            result.setDailyPowerGeneration(BigDecimal.ZERO);
        }

        return result;
    }

}
